import '@ant-design/compatible/assets/index.css';
import { Card, Col, Row, Tag, Tree, Input } from 'antd';
import { connect } from 'dva';
import React from 'react';
import enums from '../../../../public/enums';
import styles from '../../../components/common/PateoTable/TableList.less';
import DescriptionList from '../../../components/DescriptionList';
import Add from './add';

const { Description } = DescriptionList;
const { Search } = Input;
//递归模糊查询
const getTreeSel = (treeArr: any, keyword: any) => {
  // let newarr = [];
  let newarr: any[] = [];
  // 1.检测数组是否存在是否为空
  if (treeArr && treeArr.length) {
    // 直接遍历
    treeArr.forEach((item: any) => {
      if (item.children && item.children.length) {
        let children = getTreeSel(item.children, keyword);
        // 递归查询
        let obj = {
          ...item,
          children,
        };
        if (children && children.length) {
          newarr.push(obj);
        } else if (item.orgName.includes(keyword)) {
          newarr.push({ ...item });
        }
      } else {
        if (item.orgName.includes(keyword)) {
          newarr.push(item);
        }
      }
    });
  }
  return newarr;
};
// noinspection JSUnusedGlobalSymbols
@connect((state: any) => ({
  http: state.http,
  org: state.org,
  basedata: state.basedata,
}))
export default class org extends React.PureComponent<any, any> {
  state = {
    expandedKeys: [],
    autoExpandParent: true,
    delOrg: false,
    selectedData: undefined,
    details: {},
    searchValue: '',
    newTreeData: [],
    currentOrgType: null,
  };
  componentDidMount() {
    const { dispatch } = this.props;
    // 父级菜单选项
    dispatch({
      type: 'org/fetchTree',
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'org/initData',
    });
  }

  //点击树节点时触发的事件
  onSelect = (selectedKeys: any, e: any) => {
    // if (e.selected) {
    //   // 详情
    //   if (e.node && e.node.props && e.node.props.children && e.node.props.children.length > 0) {
    //     this.setState({ delOrg: false, selectedData: e.node });
    //   } else {
    //     this.setState({ delOrg: true, selectedData: e.node });
    //   }
    // } else {
    //   this.setState({ details: {} });
    //   this.setState({ delOrg: false });
    // }
    console.log(e.node);
    this.setState({
      details: e.node || {},
      delOrg: !!e.selected,
      currentOrgType: e.node?.orgType,
    });
  };
  onExpand = (expandedKeys: any) => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  };

  /*
   * 点击删除组织时，
   * 发送删除，并更新dealer列表，同时删除的组织会加入到导入界面中
   * */
  hanldeRemove = (id: any) => {
    const { dispatch, form } = this.props;
    form.validateFields((err: any, fieldsValue: any) => {
      if (err) return;
      dispatch({
        type: 'org/remove',
        payload: id,
        callback: (response: any) => {},
      });
    });
  };

  hanldClearDetails = () => {
    this.setState({
      details: {},
    });
  };

  render() {
    const { delOrg, autoExpandParent, expandedKeys, details, currentOrgType } = this.state;
    const {
      org: { loading: orgLoading, treeData },
      dispatch,
      location: { pathname = '/' },
    } = this.props;
    const onChange = (e: any) => {
      let value = e.target.value;
      this.setState({
        searchValue: value,
      });
      const data = getTreeSel(treeData, value);
      this.setState({
        newTreeData: data,
      });
    };
    return (
      <div style={{ background: '#ECECEC' }}>
        <Row gutter={16}>
          {/*显示左侧的树形控件*/}
          <Col xl={8} lg={12} md={12} sm={24} xs={24}>
            <Card
              style={{ minHeight: document.body.clientHeight - 100 }}
              title={
                <span style={{ fontSize: 16 }}>
                  组织机构{' '}
                  <span style={{ fontSize: 12, color: '#999' }}>
                    组织选中后，再点击一下可以取消选中
                  </span>
                </span>
              }
              loading={orgLoading}
              bordered={false}
              hoverable
              type="inner"
            >
              <Add
                hanldClearDetails={this.hanldClearDetails.bind(this)}
                pathname={pathname}
                delOrg={delOrg}
                changeDelOrg={() => {
                  this.setState({ delOrg: false });
                }}
                details={details}
                dispatch={dispatch}
                parentOrgType={currentOrgType}
              />
              {
                /*如果树不为空加载出树*/
                treeData && treeData.length ? (
                  <div>
                    <Search
                      style={{ marginBottom: 8 }}
                      placeholder="请输入组织名称"
                      onChange={onChange}
                      allowClear
                    />
                    <div style={{ height: document.body.clientHeight - 255, overflow: 'auto' }}>
                      <Tree
                        onSelect={this.onSelect}
                        onExpand={this.onExpand} //展开收起节点时触发
                        expandedKeys={expandedKeys} //展开指定的树节点
                        autoExpandParent={autoExpandParent} //是否自动展开父节点
                        treeData={this.state.searchValue ? this.state.newTreeData : treeData}
                        fieldNames={{
                          title: 'orgName',
                          key: 'orgCode',
                        }}
                      />
                    </div>
                  </div>
                ) : null
              }
            </Card>
          </Col>
          <Col xl={16} lg={12} md={12} sm={24} xs={24}>
            <Card
              style={{ height: document.body.clientHeight - 100, overflow: 'auto' }}
              title={<span style={{ fontSize: 16 }}>组织信息</span>}
              bordered={false}
              hoverable
              type="inner"
            >
              {details && details.sid && (
                <DescriptionList col={1} gutter={10} size="large">
                  <Description term="组织名称">
                    <Tag color="purple">
                      <span style={{ fontSize: 16 }}>{details.orgName}</span>
                    </Tag>
                  </Description>
                  <Description term="组织编码">
                    <Tag color="blue">
                      <span style={{ fontSize: 16 }}>{details.orgCode}</span>
                    </Tag>
                  </Description>
                  <Description term="组织类型">
                    <span style={{ fontSize: 16 }}>
                      {(() => {
                        if (details.orgType) {
                          let findText = enums.orgType.array.find(
                            (e) => e.value == details.orgType,
                          );
                          return findText ? findText.label : details.orgType;
                        } else {
                          return '';
                        }
                      })()}
                    </span>
                  </Description>
                  <Description term="组织简介">
                    <span style={{ fontSize: 16 }}>{details.orgDesc}</span>
                  </Description>
                </DescriptionList>
              )}
            </Card>
          </Col>
        </Row>
      </div>
    );
  }
}
